<?php
/***********************************************************
 * 分类栏目管理
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\common\model\Arctype as Arctypemodel;
use app\common\logic\ArctypeLogic;
use app\admin\model\FieldType;
use app\admin\model\Single;

class Arctype extends Base
{
    public $fieldLogic;
    // 栏目对应模型ID
    public $arctype_channel_id = '';
    // 允许发布文档的模型ID
    public $allowReleaseChannel = [];
    // 禁用的目录名称
    public $disableDirname = [];
    // 默认模板
    public $tpl_theme = '';
    // 权限
    public $popedom = '';
    public function initialize() {
        parent::initialize();
        $this->fieldLogic = new FieldType();
        $gzpcfglobal = get_global();
        $this->allowReleaseChannel = $gzpcfglobal['allow_release_channel'];
        $this->arctype_channel_id = $gzpcfglobal['arctype_channel_id'];
        $this->disableDirname = $gzpcfglobal['disable_dirname'];
        $this->tpl_theme = tpCache('system.system_tpl_theme');
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
    }

    // 栏目管理
    public function index()
    {
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        $gzpcfglobal = get_global();
        if (Request::isAjax()) {
            $channeltype_list = getChanneltypeList();
            $arctype_list = array();
            // 目录列表
            $arctypeLogic = new ArctypeLogic(); 
            $where=[];
            $where[] =['is_del','=',0]; // 回收站功能
            $arctype_list = $arctypeLogic->arctype_list(0, 0, false, 0, $where, false);
            foreach ($arctype_list as $key=>$val){
                if($val['current_channel'] != 6){
                    $total = get_total_arc($val['id']);
                    $arctype_list[$key]['typename'] = $val['typename']."<font class='wendan'>（文档：".$total."条）</font>";
                }
                $arctype_list[$key]['channeltypename'] = $channeltype_list[$val['current_channel']]['title'];
                $arctype_list[$key]['typeurl'] = get_typeurl($val);
            }
            $arctype_list = array_merge($arctype_list);
            if($arctype_list){
                $result = ['code' => 0, 'msg' => 'ok','data' => $arctype_list];
                return json($result);            
            }else{
                $result = ['code' => 1, 'msg' => 'ok','data' =>''];
                return json($result);       
            }
        }
        $channeltype_list = getChanneltypeList();
        $this->assign('json_channeltype_list', json_encode($channeltype_list));
        // 栏目最多级别
        $arctype_max_level = intval($gzpcfglobal['arctype_max_level']);
        $this->assign('arctype_max_level', $arctype_max_level);
        $typeid = input('param.typeid/d',0);
        $this->assign('typeid',$typeid);
        return $this->fetch();
    }

    // 新增 
    public function add()
    {
        $result = ['status' => false,'msg' => '失败','data' => '','url' => ''];
        // 防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["add"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                    return $result;                    
                }
            }
            $post = input('param.');
            if ($post) {
                // 目录名称
                $post['dirname'] = func_preg_replace([' ','　'], '', $post['dirname']);
                $dirname = $this->get_dirname($post['typename'], $post['dirname']);
                // 检测
                if (!empty($post['dirname']) && !$this->dirname_unique($post['dirname'])) {
                    $result = ['status' => false,'msg' => '目录名称与系统内置冲突，请更改！'];
                    return $result;
                }
                $dirpath = rtrim($post['dirpath'],'/');
                // 临时代码，当能支持静态页面生成，再去掉
                $dirpath = $dirpath . '/' . $dirname;
                $typelink = !empty($post['is_part']) ? $post['typelink'] : '';
                // 获取顶级模型ID
                if (empty($post['parent_id'])) {
                    $channeltype = $post['current_channel'];
                } else {
                    $channeltype = Db::name('arctype')->where('id', $post['parent_id'])->value('channeltype');
                }
                // SEO描述
                $seo_description = $post['seo_description'];
                // 处理自定义字段值
                $addonField = array();
                if (!empty($post['addonField'])) {
                    $addonField = $this->fieldLogic->handleAddonField($this->arctype_channel_id, $post['addonField']);
                }
                $newData = array(
                    'dirname' => $dirname,
                    'dirpath'   => $dirpath,
                    'typelink' => $typelink,
                    'channeltype'   => $channeltype,
                    'current_channel' => $post['current_channel'],
                    'seo_keywords' => str_replace('，', ',', $post['seo_keywords']),
                    'seo_description' => $seo_description,
                    'admin_id'  => Session::get('admin_id'),
                    'sort_order'    => 100,
                    'add_time'  => getTime(),
                    'update_time'  => getTime(),
                );
                $data = array_merge($post, $newData, $addonField);
                $Arctypemodel = new Arctypemodel();
                $insertId = $Arctypemodel->addData($data);
                if($insertId){
                    $result = ['status' => true,'msg' => '操作成功','url'=>url('/arctype/index', ['typeid'=>$insertId])->suffix(false)->domain(true)->build()];
                    return $result;
                }
            }
            $result = ['status' => false,'msg' => '操作失败'];
            return $result;
        }
        $assign_data = array();
        $channeltype_list = Db::name('channel_type')->where('status',1)->column('id,title,nid', 'id');
        $this->assign('channeltype_list', $channeltype_list);
        // 新增栏目在指定的上一级栏目下
        $parent_id = input('param.parent_id/d');
        $grade = 0;
        $current_channel = '';
        $predirpath = '';
        $ptypename = '';
        if (0 < $parent_id) {
            $info = Db::name('arctype')->where('id',$parent_id)->find();
            if ($info) {
                // 级别
                $grade = $info['grade'] + 1;
                // 模型
                $current_channel = $info['current_channel'];
                // 上级目录
                $predirpath = $info['dirpath'];
                // 上级栏目名称
                $ptypename = $info['typename'];
            }
        }
        $this->assign('predirpath', $predirpath);
        $this->assign('parent_id', $parent_id);
        $this->assign('ptypename', $ptypename);
        $this->assign('grade',$grade);
        $this->assign('current_channel',$current_channel);
        // 发布文档的模型ID，用于是否显示文档模板列表
        $js_allow_channel_arr = '[';
        foreach ($this->allowReleaseChannel as $key => $val) {
            if ($key > 0) {
                $js_allow_channel_arr .= ',';
            }
            $js_allow_channel_arr .= $val;
        }
        $js_allow_channel_arr = $js_allow_channel_arr.']';
        $this->assign('js_allow_channel_arr', $js_allow_channel_arr);
        // 模板列表
        $templateList = $this->ajax_getTemplateList('add');
        $this->assign('templateList', json_encode($templateList));
        // 自定义字段
        $FieldLogic = new \app\admin\logic\FieldLogic;
        $assign_data['addonFieldExtList'] = $FieldLogic->getTabelFieldList($this->arctype_channel_id);
        $assign_data['aid'] = 0;
        $assign_data['channeltype'] = 6;
        $assign_data['nid'] = 'arctype';
        $this->assign($assign_data);
        return $this->fetch();
    }

    // 编辑 
    public function edit()
    {
        $result = ['status' => false,'msg' => '失败','data' => ''];
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            } 
            $post = input('param.');
            if(!empty($post['id'])){
                // 自己的上级不能是自己
                if (intval($post['id']) == intval($post['parent_id'])) {
                    $result = ['status' => false,'msg' => '自己不能成为自己的上级栏目'];
                    return $result;
                }
                // 目录名称
                $post['dirname'] = func_preg_replace([' ','　'], '', $post['dirname']);
                $dirname = $this->get_dirname($post['typename'], $post['dirname'], $post['id']);
                // 检测
                if (!empty($post['dirname']) && !$this->dirname_unique($post['dirname'], $post['id'])) {
                    $result = ['status' => false,'msg' => '目录名称与系统内置冲突，请更改！'];
                    return $result;
                }
                $dirpath = rtrim($post['dirpath'], '/');
                $typelink = !empty($post['is_part']) ? $post['typelink'] : '';
                // 最顶级模型ID
                $channeltype = $post['channeltype'];
                // 当前更改的等级
                $grade = $post['grade']; 
                // 根据栏目ID获取最新的最顶级模型ID
                if (intval($post['parent_id']) > 0) {
                    $arctype_row = Db::name('arctype')->field('grade,channeltype')->where('id', $post['parent_id'])->find();
                    $channeltype = $arctype_row['channeltype'];
                    $grade = $arctype_row['grade'] + 1;
                }
                // SEO描述
                $seo_description = $post['seo_description'];
                // 处理自定义字段值
                $addonField = array();
                if (!empty($post['addonField'])) {
                    $addonField = $this->fieldLogic->handleAddonField($this->arctype_channel_id, $post['addonField']);
                }
                $newData = array(
                    'dirname' => $dirname,
                    'dirpath'   => $dirpath,
                    'typelink' => $typelink,
                    'channeltype'   => $channeltype,
                    'grade' => $grade,
                    'seo_keywords' => str_replace('，', ',', $post['seo_keywords']),
                    'seo_description' => $seo_description,
                    'update_time'  => getTime(),
                );
                $data = array_merge($post, $newData, $addonField);
                unset($data['file'],$data['oldgrade']);
                $Arctypemodel = new Arctypemodel();
                $r = $Arctypemodel->pcfupdateData($data);
                if($r){
                    // 当前栏目以及所有子孙栏目的静态HTML保存路径的变动
                    $subSaveData = [];
                    $hasChildrenRow = $Arctypemodel->getHasChildren($post['id'], true);
                    foreach ($hasChildrenRow as $key => $val) {
                        $dirpathArr = explode('/', trim($val['dirpath'], '/'));
                        $dirpathArr[$grade] = $dirname;
                        $dirpath = '/'.implode('/', $dirpathArr);
                        $subSaveData[] = [
                            'id'            => $val['id'],
                            'dirpath'       => $dirpath,
                            'update_time'   => getTime(),
                        ];
                    }
                    if (!empty($subSaveData)) {
                        foreach ($subSaveData as $key => $value) {
                            Db::name('arctype')->save($value);
                        } 
                    }
                    $result = ['status' => true,'msg' => '操作成功','url'=>url('/arctype/index', ['typeid'=>$post['id']])->suffix(false)->domain(true)->build()];
                    return $result;
                }
            }else{
               $result = ['status' => false,'msg' => '操作失败'];
               return $result;                
            }

        }
        $assign_data = array();
        $id = input('param.id/d');
        $info = Db::name('arctype')->where('id',$id)->find();
        if (empty($info)) {
            return $this->errorNotice('数据不存在，请联系管理员！',true,3,false);
        }
        // 栏目图片处理
        $info['litpic'] = handle_subdir_pic($info['litpic']);
        $this->assign('field',$info);

        // 获得上级目录路径
        if (!empty($info['dirpath'])) {
            $predirpath = preg_replace('/\/([^\/]*)$/i', '', $info['dirpath']);
        } else {
            $predirpath = '';
        }
        $this->assign('predirpath',$predirpath);
        // 是否有子栏目
        $Arctypemodel = new Arctypemodel();
        $hasChildren = $Arctypemodel->hasChildren($id);
        if ($hasChildren > 0) {
            $select_html = Db::name('arctype')->where('id', $info['parent_id'])->value('typename');
            $select_html = !empty($select_html) ? $select_html : '顶级栏目';
        } else {
            // 所属栏目
            $select_html = '<option value="0" data-grade="-1" data-dirpath="'.tpCache('seo.seo_html_arcdir').'">顶级栏目</option>';
            $selected = $info['parent_id'];
            $global = get_global('global');
            $arctype_max_level = intval($global['arctype_max_level']);
            $arctypeLogic = new ArctypeLogic();
            $options = $arctypeLogic->arctype_list(0, $selected, false, $arctype_max_level - 1);
            foreach ($options AS $var)
            {
                $select_html .= '<option value="' . $var['id'] . '" data-grade="' . $var['grade'] . '" data-dirpath="'.$var['dirpath'].'"';
                $select_html .= ($selected == $var['id']) ? "selected='ture'" : '';
                $select_html .= ($id == $var['id']) ? "disabled='ture' style='background-color:#f5f5f5;'" : '';
                $select_html .= '>';
                if ($var['level'] > 0)
                {
                    $select_html .= str_repeat('&nbsp;', $var['level'] * 4);
                }
                $select_html .= htmlspecialchars(addslashes($var['typename'])) . '</option>';
            }
        }
        $this->assign('select_html',$select_html);
        $this->assign('hasChildren',$hasChildren);
        $channeltype_list = Db::name('channel_type')->where('status',1)->column('id,title,nid,ctl_name', 'id');
        // 模型对应模板文件不存在报错
        if (!isset($channeltype_list[$info['current_channel']])) {
            $row = Db::name('channel_type')->where('id', $info['current_channel'])->find();
            $file = 'lists_'.$row['nid'].'.html';
            return $this->errorNotice($row['title'].'缺少模板文件'.$file,true,3,false);
        }
        // 选项卡内容的链接
        $ctl_name = $channeltype_list[$info['current_channel']]['ctl_name'];
        $list_url = url("{$ctl_name}/index")."?typeid={$id}";
        $this->assign('list_url', $list_url);
        $this->assign('channeltype_list', $channeltype_list);
        // 发布文档的模型ID，用于是否显示文档模板列表
        $js_allow_channel_arr = '[';
        foreach ($this->allowReleaseChannel as $key => $val) {
            if ($key > 0) {
                $js_allow_channel_arr .= ',';
            }
            $js_allow_channel_arr .= $val;
        }
        $js_allow_channel_arr = $js_allow_channel_arr.']';
        $this->assign('js_allow_channel_arr', $js_allow_channel_arr);
        // 模板列表
        $templateList = $this->ajax_getTemplateList('edit', $info['templist'], $info['tempview']);
        $this->assign('templateList', json_encode($templateList));
        // 自定义字段
        $FieldLogic = new \app\admin\logic\FieldLogic;
        $assign_data['addonFieldExtList'] = $FieldLogic->getTabelFieldList($this->arctype_channel_id, $id);
        $assign_data['aid'] = $id;
        $assign_data['channeltype'] = 6;
        $assign_data['nid'] = 'arctype';
        $this->assign($assign_data);
        return $this->fetch();
    }

    // 单页编辑
    public function single_edit()
    {
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        $result = ['status' => false,'msg' => '失败','data' => '','url' => ''];
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            } 
            $post = input('param.');
            $typeid = input('param.typeid/d', 0);
            if(!empty($typeid)){
                $info = Db::name('arctype')->field('id,typename,current_channel')->where('id' , $typeid)->find();
                $aid = Db::name('archives')->where(['typeid' => $typeid,'channel' => 6])->value('aid');
                // 修复新增单页栏目的关联数据不完善，进行修复
                if (empty($aid)) {
                    $archivesData = array(
                        'title' => $info['typename'],
                        'typeid'=> $info['id'],
                        'channel'   => $info['current_channel'],
                        'sort_order'    => 100,
                        'add_time'  => getTime(),
                        'update_time'     => getTime(),
                    );
                    $aid = Db::name('archives')->insertGetId($archivesData);
                }
                if (!isset($post['addonFieldExt'])) {
                    $post['addonFieldExt'] = array();
                }
                $updateData = array(
                    'aid'   => $aid,
                    'typename' => $info['typename'],
                    'addonFieldExt' => $post['addonFieldExt'],
                );
                $Single = new Single();
                $Single->afterSave($aid, $updateData, 'edit');
                Cache::clear("arctype");
                $result = ['status' => true,'msg' => '操作成功','url' => url('/arctype/index')->suffix(false)->domain(true)->build()];
                return $result;
            }
            $result = ['status' => false,'msg' => '操作失败'];
            return $result;
        }

        $assign_data = array();
        $typeid = input('param.typeid/d');
        $info = Db::name('arctype')->where('id',$typeid)->find();
        if (empty($info)) {
            return $this->errorNotice('数据不存在，请联系管理员！',true,3,false);
        }
        $assign_data['info'] = $info;
        $FieldLogic = new \app\admin\logic\FieldLogic;
        $addonFieldExtList = $FieldLogic->getChannelFieldList(6, false, $typeid, $info);
        $channelfieldBindRow = Db::name('channelfield_bind')->where('typeid','IN', [0,$typeid])->field('field_id')->select()->toArray();
        foreach ($channelfieldBindRow as $key => $value) {
            $channelfieldBindRow[$key] = $value['field_id'];
        }
        if (!empty($channelfieldBindRow)) {
            foreach ($addonFieldExtList as $key => $val) {
                if (!in_array($val['id'], $channelfieldBindRow)) {
                    unset($addonFieldExtList[$key]);
                }
            }
        }
        $assign_data['addonFieldExtList'] = $addonFieldExtList;
        $assign_data['aid'] = $typeid;
        $assign_data['channeltype'] = 6;
        $assign_data['nid'] = 'single';
        $goback = input('param.goback/d');
        if ($goback == 1) {
            $gourl = url('/arctype/index')->suffix(false)->domain(true)->build();
        }
        $assign_data['gourl'] = $gourl ? $gourl :'';
        $this->assign($assign_data);
        return $this->fetch();
    }

    // 获取栏目的目录名称，确保唯一性 
    private function get_dirname($typename = '', $dirname = '', $id = 0)
    {
        $id = intval($id);
        if (!trim($dirname) || empty($dirname)) {
            $dirname = get_pinyin($typename);
        }
        if (strval(intval($dirname)) == strval($dirname)) {
            $dirname .= get_rand_str(3,0,2);
        }
        $dirname = preg_replace('/(\s)+/', '_', $dirname);
        if (!$this->dirname_unique($dirname, $id)) {
            $nowDirname = $dirname.get_rand_str(3,0,2);
            return $this->get_dirname($typename, $nowDirname, $id);
        }
        return $dirname;
    }

    // 判断目录名称的唯一性 
    private function dirname_unique($dirname = '', $typeid = 0)
    {
        $result = Db::name('arctype')->column('id,dirname', 'id');
        if (!empty($result)) {
            if (0 < $typeid) unset($result[$typeid]);
            !empty($result) && $result = get_arr_column($result, 'dirname');
        }
        empty($result) && $result = [];
        $disableDirname = array_merge($this->disableDirname, $result);
        if (in_array(strtolower($dirname), $disableDirname)) {
            return false;
        }
        return true;
    }

    // 通过模型获取栏目 
    public function ajax_get_arctype($channeltype = 0)
    {
        $arctypeLogic = new ArctypeLogic();
        $arctype_max_level = intval(config('global.arctype_max_level'));
        $options = $arctypeLogic->arctype_list(0, 0, false, $arctype_max_level, array('channeltype'=>$channeltype));
        $select_html = '<option value="0" data-grade="-1">顶级栏目</option>';
        foreach ($options AS $var)
        {
            $select_html .= '<option value="' . $var['id'] . '" data-grade="' . $var['grade'] . '" data-dirpath="'.$var['dirpath'].'"';
            $select_html .= '>';
            if ($var['level'] > 0)
            {
                $select_html .= str_repeat('&nbsp;', $var['level'] * 4);
            }
            $select_html .= htmlspecialchars(addslashes($var['typename'])) . '</option>';
        }
        $returndata = ['status' => 1,'select_html' => $select_html];
        return $returndata;
    }

    // 获取栏目的拼音 
    public function ajax_get_dirpinyin($typename = '')
    {
        $typename = input('param.typename/s');
        $pinyin = get_pinyin($typename);
        $returndata = ['status' => 1,'msg' => $pinyin];
        return $returndata;
    }

    // 检测文件保存目录是否存在 
    public function ajax_check_dirpath()
    {
        $dirpath = input('param.dirpath/s');
        $id = input('param.id/d');
        $map = array('dirpath' => $dirpath);
        if (intval($id) > 0) {
            $map['id'] = array('<>', $id);
        }
        $result = Db::name('arctype')->where($map)->find();
        if (!empty($result)) {
            $returndata = ['status' => 0,'msg' => '文件保存目录已存在，请更改'];
            return $returndata;
        } else {
            $returndata = ['status' => 1,'msg' => '文件保存目录可用'];
            return $returndata;
        }
    }

    // 伪删除 
    public function pseudo_del()
    {
        $result = ['status' => false,'msg' => '失败','data' => ''];
        if (Request::isPost()){
            //验证权限
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $post = input('param.');
            $post['del_id'] = eyIntval($post['del_id']);
            $Arctypemodel = new Arctypemodel();
            $r = $Arctypemodel->pseudo_del($post['del_id']);
            if ($r) {
                $result = ['status' => true,'msg' => '删除成功'];
                return $result;
            } else {
                $result = ['status' => false,'msg' => '删除失败'];
                return $result;
            }
        }
        $result = ['status' => false,'msg' => '非法访问'];
        return $result;
    }

    // 模板列表 
    public function ajax_getTemplateList($opt = 'add', $templist = '', $tempview = '')
    {
        $result = ['status' => false,'msg' => '失败','data' => ''];
        $planPath = "template/{$this->tpl_theme}/pc";
        $dirRes   = opendir($planPath);
        $view_suffix = config('template.view_suffix') ? config('template.view_suffix') : 'html';
        // 模板PC目录文件列表
        $templateArr = array();
        while($filename = readdir($dirRes))
        {
            if (in_array($filename, array('.','..'))) {
                continue;
            }
            array_push($templateArr, $filename);
        }
        !empty($templateArr) && asort($templateArr);
        $templateList = array();
        $channelList = Db::name('channel_type')->select()->toArray();
        foreach ($channelList as $k1 => $v1) {
            $l = 1;
            $v = 1;
            $lists = ''; // 销毁列表模板
            $view = ''; // 销毁文档模板
            $templateList[$v1['id']] = array();
            foreach ($templateArr as $k2 => $v2) {
                $v2 = iconv('GB2312', 'UTF-8', $v2);
                if ('add' == $opt) {
                    $selected = 0; // 默认选中状态
                } else {
                    $selected = 1; // 默认选中状态
                }
                preg_match('/^(lists|view)_'.$v1['nid'].'(_(.*))?\.'.$view_suffix.'/i', $v2, $matches1);
                if (!empty($matches1)) {
                    $selectefile = '';
                    if ('lists' == $matches1[1]) {
                        $lists .= '<option value="'.$v2.'" ';
                        $lists .= ($templist == $v2 || $selected == $l) ? " selected='true' " : '';
                        $lists .= '>'.$v2.'</option>';
                        $l++;
                    } else if ('view' == $matches1[1]) {
                        $view .= '<option value="'.$v2.'" ';
                        $view .= ($tempview == $v2 || $selected == $v) ? " selected='true' " : '';
                        $view .= '>'.$v2.'</option>';
                        $v++;
                    }
                }
            }
            $nofileArr = [];
            if ('add' == $opt) {
                if (empty($lists)) {
                    $lists = '<option value="">无</option>';
                    $nofileArr[] = "lists_{$v1['nid']}.{$view_suffix}";
                }
                if (empty($view)) {
                    $view = '<option value="">无</option>';
                    if (!in_array($v1['nid'], ['single'])) {
                        $nofileArr[] = "view_{$v1['nid']}.{$view_suffix}";
                    }
                }
            } else {
                if (empty($lists)) {
                    $nofileArr[] = "lists_{$v1['nid']}.{$view_suffix}";
                }
                $lists = '<option value="">请选择模板…</option>'.$lists;
                if (empty($view)) {
                    if (!in_array($v1['nid'], ['single'])) {
                        $nofileArr[] = "view_{$v1['nid']}.{$view_suffix}";
                    }
                }
                $view = '<option value="">请选择模板…</option>'.$view;
            }
            $msg = '';
            if (!empty($nofileArr)) {
                $msg = '<font color="red">该模型缺少模板文件：'.implode(' 和 ', $nofileArr).'</font>';
            }
            $templateList[$v1['id']] = array(
                'lists' => $lists,
                'view' => $view,
                'msg'    => $msg,
                'nid'    => $v1['nid'],
            );
        }
        if (Request::isPost()) {
            $result = ['status' => true,'msg' => '请求成功','data' => $templateList];
            return $result;
        } else {
            return $templateList;
        }
    }

    // 新建模板文件  
    public function ajax_newtpl()
    {
        $result = ['status' => false,'msg' => '失败','data' => ''];
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["add"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                    return $result;                    
                }
            }
            $post = input('param.');
            $content = input('param.content');
            $view_suffix = config('template.view_suffix') ? config('template.view_suffix') : 'html';
            $type = isset($post['type']) ? $post['type']:'';
            $nid = isset($post['nid']) ? $post['nid']:'';
            $pcffilename = isset($post['filename']) ? $post['filename']:'';
            if (!empty($pcffilename)) {
                if (!preg_match('/^[0-9a-z]{4,10}$/i',$pcffilename)) {
                    $result = ['status' => false,'msg' => '文件名称只允许4位到10位的纯字母或者字母和数字组合','data' => ['focus'=>'filename']];
                    return $result;
                }
                if(preg_match("/^\d+$/i",$pcffilename)){
                    $result = ['status' => false,'msg' => '不能是纯数字','data' => ['focus'=>'filename']];
                    return $result;
                }
                $filename = "{$type}_{$nid}_{$pcffilename}.{$view_suffix}";
            } else {
                $filename = "{$type}_{$nid}.{$view_suffix}";
            }
            $content = !empty($content) ? $content : '';
            $tpldirpath = !empty($post['tpldir']) ? '/template/'.$this->tpl_theme.'/'.trim($post['tpldir']) : "/template/{$this->tpl_theme}/pc";
            if (file_exists(ROOT_PATH.'public/'.ltrim($tpldirpath, '/').'/'.$filename)) {
                $result = ['status' => false,'msg' => '文件名称已经存在，请重新命名！','data' => ['focus'=>'filename']];
                return $result;
            }
            $nosubmit = input('param.nosubmit/d');
            if (1 == $nosubmit) {
                $result = ['status' => true,'msg' => '检测通过'];
                return $result;
            }
            $filemanagerLogic = new \app\admin\logic\FilemanagerLogic;
            $r = $filemanagerLogic->editFile($filename, $tpldirpath, $content);
            if ($r === true) {
                $result = ['status' => true,'msg' => '操作成功','data' => ['filename'=>$filename,'type'=> $post['type']]];
                return $result;
            } else {
                $result = ['status' => false,'msg' => $r];
                return $result;
            }
        }
        $type = input('param.type/s');
        $nid = input('param.nid/s');
        $tpldirList = glob("template/{$this->tpl_theme}/*");
        foreach ($tpldirList as $key => $val) {
            if (!preg_match('/template\/'.$this->tpl_theme.'\/(pc|mobile)$/i', $val)) {
                unset($tpldirList[$key]);
            } else {
                $tpldirList[$key] = preg_replace('/^(.*)template\/'.$this->tpl_theme.'\/(pc|mobile)$/i', '$2', $val);
            }
        }
        !empty($tpldirList) && arsort($tpldirList);
        $this->assign('tpldirList', $tpldirList);
        $this->assign('type', $type);
        $this->assign('nid', $nid);
        return $this->fetch();
    }

}